import { Sensor } from "../Sensor"
import { MqttUtil } from '../../utils/MqttUtil';
import HashMap from '@ohos.util.HashMap';
/**
 * 用于Mqtt的传感器收发装置
 */
export class MqttSensor implements Sensor {
  // JS 中弱引用的Map,它引用的数据不会被计入引用数量。
  private static mp: HashMap<string, MqttSensor> = new HashMap();

  public value: number = 0;
  private topic: string;
  sensorName: string;
  icon;

  constructor() {
  };

  close = () => {
    MqttUtil.unsubscribe(this.topic)
    MqttSensor.mp.remove(this.topic)
    return;
  }

  public init(topic: string, sensorName: string, icon) {
    this.topic = topic;
    this.sensorName = sensorName;
    this.icon = icon;

    // console.info("anran-mp"+MqttSensor.mp)
    MqttSensor.mp.set(this.topic, this);
    MqttUtil.subscribe(this.topic);
    return this;
  }

  /**
   "topic":"test",
   "payload":
   "{  \"msg\": \"hello222\"}",
   "qos":0,
   "retained":0,
   "dup":0,
   "msgid":0
   */
  public static update = (e: object, data) => {

    console.info("anran0_update_" + JSON.stringify(data.payload))
    // 更新数据
    // if (MqttSensor.mp.get(data.topic))

    MqttSensor.mp.get(data.topic).value = JSON.parse(data.payload).value.toFixed(2);

    // MqttSensor.mp.get(data.topic).value
  }
}